package com.blog.boot.webapp.controller.common;

import cn.dsna.util.images.ValidateCode;
import com.sun.org.apache.bcel.internal.generic.RETURN;
import org.omg.CosNaming.NamingContextPackage.NotFound;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Controller
@RequestMapping("/system")
public class SystemController extends BaseController implements ErrorController {

    private final static String NOTFOUND = "/error/404.html";

    private final static String SYSTEMERROR = "/error/500.html";

    @RequestMapping(value = "/vacode", method = { RequestMethod.POST, RequestMethod.GET })
    @ResponseBody
    public void outVacode(String type,HttpServletResponse response, HttpServletRequest request) {
        ValidateCode va = new ValidateCode(116, 36, 4, 5);
        String code = va.getCode();
        HttpSession session = request.getSession();
        if("login".equals(type)){
            session.setAttribute("login_vercode", code);
        }else if("regist".equals(type)){
            session.setAttribute("regist_vercode", code);
        }else{
            return ;
        }
        try {
            va.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @RequestMapping("/error")
    public String handleError(HttpServletRequest request){
        //获取statusCode:401,404,500
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if(400 <= statusCode &&  statusCode < 500){
            return "forward:"+NOTFOUND;
        }else if(500 <= statusCode){
            return "forward:"+SYSTEMERROR;
        }
        return "forward:"+SYSTEMERROR;
    }

    @Override
    public String getErrorPath() {
        return "forward:"+SYSTEMERROR;
    }
}
